﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Script.Serialization;
using LCA.Ajax;
using LCA.Common.Calculation;

public partial class Services_ImpactFactorCalculationService : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(Request.InputStream);

        string str = sr.ReadToEnd();
        var table = new JavaScriptSerializer().Deserialize<dynamic>(str);

        CalResult result = ProcessData(table);
        string strResult = new JavaScriptSerializer().Serialize(result);

        Response.AddHeader("Content-Type", "text/plain");
        Response.Write(strResult);
        Response.Flush();
        Response.End();
    }

    private CalResult ProcessData(dynamic table)
    {
        string opt = table["opt"];
        CalResult result = null;
        switch (opt)
        {
            case "calculate":
                result = Calculate(table);
                break;
            
        }

        return result;
    }

    private CalResult Calculate(dynamic table)
    {
        CalResult result = new CalResult();
        try
        {
            Guid systemId = Guid.Parse(table["systemId"]);

            // List<ImpactFactorCalculationResult> data = GetData();
            CalculationManager mgr = new CalculationManager(systemId);
            mgr.Calculate();
            
            var data = mgr.GetResult();
            var hotspotList = mgr.GetHotspotList();

            result.Result = true;
            result.Data = new JavaScriptSerializer().Serialize(data);
            result.Hotspot = new JavaScriptSerializer().Serialize(hotspotList);
        }
        catch (Exception ex)
        {
            result.Result = false;
            result.Data = ex.Message;
        }

        return result;
    }

    //private List<ImpactFactorCalculationResult> GetData()
    //{
    //    List<ImpactFactorCalculationResult> data = new List<ImpactFactorCalculationResult>();
    //    data.Add(new ImpactFactorCalculationResult { 
    //        FactorId = Guid.Parse("6DB5C865-082D-4B15-B982-BC2C9102A4E6"),
    //        FactorName = "Greenhouse",
    //        Impact = 51.21M,
    //        UnitName = "Kg" });

    //    data.Add(new ImpactFactorCalculationResult
    //    {
    //        FactorId = Guid.Parse("6DB5C865-082D-4B15-B982-BC2C9102A4E6"),
    //        FactorName = "Solid Waste",
    //        Impact = 100.56M,
    //        UnitName = "Kg"
    //    });

    //    data.Add(new ImpactFactorCalculationResult
    //    {
    //        FactorId = Guid.Parse("6DB5C865-082D-4B15-B982-BC2C9102A4E6"),
    //        FactorName = "Pesticides",
    //        Impact = 98.4M,
    //        UnitName = "-"
    //    });
    //    return data;
    //}
}
